import tkinter as tk
from tkinter import ttk, messagebox, simpledialog
import json
import os

# Global variables
FILENAME = "pokemon_collection.txt"
pokemons = []
tree = None
status_var = None

# PocketManager functions
def create_file_if_not_exists(filename):
    if not os.path.exists(filename):
        with open(filename, 'w', encoding='utf-8') as f:
            f.write('[]')

def check_file_exists(filename):
    return os.path.exists(filename)

def save_to_file(data, filename):
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

def load_from_file(filename):
    if not os.path.exists(filename) or os.path.getsize(filename) == 0:
        return []
    with open(filename, 'r', encoding='utf-8') as f:
        try:
            return json.load(f)
        except json.JSONDecodeError:
            return []

def count_lines(filename):
    if not os.path.exists(filename):
        return 0
    with open(filename, 'r', encoding='utf-8') as f:
        return len(f.readlines())

def create_pokemon(data, name, type_, level):
    pokemon_id = max([p.get('id', 0) for p in data], default=0) + 1
    data.append({
        'id': pokemon_id,
        'name': name,
        'type': type_.capitalize(),
        'level': level
    })
    return pokemon_id

def release_pokemon(data, pokemon_id):
    try:
        pokemon_id = int(pokemon_id)
        return [p for p in data if p.get('id') != pokemon_id]
    except ValueError:
        return data

# GUI functions
def init_data():
    global pokemons
    create_file_if_not_exists(FILENAME)
    if count_lines(FILENAME) == 0:
        pokemons = []
        create_pokemon(pokemons, "Pikachu", "Electric", 5)
        create_pokemon(pokemons, "Charmander", "Fire", 8)
        create_pokemon(pokemons, "Golem", "Rock", 999)
        save_to_file(pokemons, FILENAME)
    else:
        pokemons = load_from_file(FILENAME)

def refresh_list():
    global tree, pokemons, status_var
    for item in tree.get_children():
        tree.delete(item)
    
    for pokemon in pokemons:
        tree.insert('', tk.END, values=(
            pokemon['id'],
            pokemon['name'],
            pokemon['type'],
            pokemon['level']
        ))
    
    status_var.set(f"Current collection: {len(pokemons)} Pokémon")

def add_pokemon():
    global pokemons
    dialog = tk.Toplevel()
    dialog.title("Add New Pokémon")
    dialog.geometry("350x250")
    dialog.resizable(False, False)
    dialog.transient(root)
    dialog.grab_set()
    dialog.configure(bg='#FFDE00')
    
    # Center the dialog
    dialog.update_idletasks()
    width = dialog.winfo_width()
    height = dialog.winfo_height()
    x = (root.winfo_width() // 2) - (width // 2) + root.winfo_x()
    y = (root.winfo_height() // 2) - (height // 2) + root.winfo_y()
    dialog.geometry(f"+{x}+{y}")
    
    # Create a styled frame
    input_frame = tk.Frame(dialog, bg='#FFDE00', padx=20, pady=20)
    input_frame.pack(fill=tk.BOTH, expand=True)
    
    tk.Label(input_frame, text="Name:", bg='#FFDE00', fg='#CC0000', 
             font=('Arial', 12, 'bold')).grid(row=0, column=0, padx=10, pady=15, sticky=tk.W)
    name_entry = tk.Entry(input_frame, width=20, font=('Arial', 11), 
                         bg='#FFFFFF', relief='solid', bd=2)
    name_entry.grid(row=0, column=1, padx=10, pady=15)
    
    tk.Label(input_frame, text="Type:", bg='#FFDE00', fg='#CC0000', 
             font=('Arial', 12, 'bold')).grid(row=1, column=0, padx=10, pady=15, sticky=tk.W)
    type_entry = tk.Entry(input_frame, width=20, font=('Arial', 11), 
                         bg='#FFFFFF', relief='solid', bd=2)
    type_entry.grid(row=1, column=1, padx=10, pady=15)
    
    tk.Label(input_frame, text="Level:", bg='#FFDE00', fg='#CC0000', 
             font=('Arial', 12, 'bold')).grid(row=2, column=0, padx=10, pady=15, sticky=tk.W)
    level_entry = tk.Entry(input_frame, width=20, font=('Arial', 11), 
                          bg='#FFFFFF', relief='solid', bd=2)
    level_entry.grid(row=2, column=1, padx=10, pady=15)
    
    def confirm():
        name = name_entry.get().strip()
        type_ = type_entry.get().strip()
        level_text = level_entry.get().strip()
        
        if not name or not type_ or not level_text:
            messagebox.showerror("Error", "All fields must be filled in!")
            return
        
        try:
            level = int(level_text)
            if level <= 0:
                raise ValueError
        except ValueError:
            messagebox.showerror("Error", "Level must be a positive integer!")
            return
        
        create_pokemon(pokemons, name, type_, level)
        refresh_list()
        dialog.destroy()
        messagebox.showinfo("Success", f"Successfully added {name} to collection!")
    
    button_frame = tk.Frame(dialog, bg='#FFDE00')
    button_frame.pack(pady=10)
    
    confirm_btn = tk.Button(button_frame, text="Confirm Add", command=confirm, 
                           bg='#CC0000', fg='white', font=('Arial', 10, 'bold'),
                           relief='raised', bd=3, padx=15, pady=5)
    confirm_btn.pack(side=tk.LEFT, padx=10)
    
    cancel_btn = tk.Button(button_frame, text="Cancel", command=dialog.destroy,
                          bg='#B3B3B3', fg='white', font=('Arial', 10, 'bold'),
                          relief='raised', bd=3, padx=15, pady=5)
    cancel_btn.pack(side=tk.LEFT, padx=10)

def release_pokemon_gui():
    global pokemons
    if not pokemons:
        messagebox.showinfo("Info", "No Pokémon in your collection!")
        return
    
    pokemon_id = simpledialog.askstring("Release Pokémon", "Enter ID of Pokémon to release:")
    if not pokemon_id:
        return
    
    try:
        pokemon_id = int(pokemon_id)
        found = any(p.get('id') == pokemon_id for p in pokemons)
        if not found:
            messagebox.showerror("Error", f"Pokémon with ID {pokemon_id} does not exist!")
            return
        
        # Get pokemon name for confirmation
        pokemon_name = next((p['name'] for p in pokemons if p['id'] == pokemon_id), "Unknown")
        
        confirm = messagebox.askyesno("Confirm Release", 
                                     f"Are you sure you want to release {pokemon_name} (ID: {pokemon_id})?\nThis action cannot be undone!")
        if confirm:
            pokemons = release_pokemon(pokemons, pokemon_id)
            refresh_list()
            messagebox.showinfo("Success", f"Released Pokémon with ID {pokemon_id}!")
    except ValueError:
        messagebox.showerror("Error", "ID must be an integer!")

def save_pokemons():
    global pokemons
    save_to_file(pokemons, FILENAME)
    messagebox.showinfo("Success", "Collection saved successfully!")

def create_pokeball_icon(canvas, x, y, size=20):
    """Create a simple pokeball icon"""
    radius = size // 2
    # Top red half
    canvas.create_arc(x-radius, y-radius, x+radius, y+radius, 
                     start=0, extent=180, fill='#CC0000', outline='black')
    # Bottom white half
    canvas.create_arc(x-radius, y-radius, x+radius, y+radius, 
                     start=180, extent=180, fill='white', outline='black')
    # Center circle
    canvas.create_oval(x-4, y-4, x+4, y+4, fill='white', outline='black')
    # Horizontal line
    canvas.create_line(x-radius, y, x+radius, y, fill='black', width=1)

def create_widgets(root):
    global tree, status_var
    
    root.title("Pokémon Collection Manager")
    root.geometry("900x650")
    root.resizable(True, True)
    root.configure(bg='#FFDE00')  # Pokemon yellow
    
    # Configure styles
    style = ttk.Style()
    style.theme_use('clam')
    
    # Configure treeview style
    style.configure("Pokemon.Treeview", 
                   background="#FFFFFF",
                   foreground="#333333",
                   fieldbackground="#FFFFFF",
                   font=('Arial', 10))
    
    style.configure("Pokemon.Treeview.Heading",
                   background="#CC0000",  # Pokemon red
                   foreground="white",
                   font=('Arial', 11, 'bold'),
                   relief="flat")
    
    style.map("Pokemon.Treeview.Heading",
             background=[('active', '#FF0000')])
    
    # Main container with pokemon theme
    main_frame = tk.Frame(root, bg='#FFDE00', padx=15, pady=15)
    main_frame.pack(fill=tk.BOTH, expand=True)
    
    # Header with Pokeball icon and title
    header_frame = tk.Frame(main_frame, bg='#FFDE00')
    header_frame.pack(fill=tk.X, pady=(0, 15))
    
    # Create pokeball icon
    icon_canvas = tk.Canvas(header_frame, width=40, height=40, bg='#FFDE00', 
                           highlightthickness=0)
    icon_canvas.pack(side=tk.LEFT, padx=(0, 10))
    create_pokeball_icon(icon_canvas, 20, 20, 30)
    
    title_label = tk.Label(header_frame, text="Pokémon Collection Manager", 
                          font=('Arial', 20, 'bold'), 
                          bg='#FFDE00', fg='#CC0000')
    title_label.pack(side=tk.LEFT)
    
    # Button frame with styled buttons
    button_frame = tk.Frame(main_frame, bg='#FFDE00')
    button_frame.pack(fill=tk.X, pady=10)
    
    # Create styled buttons
    add_btn = tk.Button(button_frame, text="➕ Add Pokémon", command=add_pokemon,
                       bg='#3B7BC2', fg='white', font=('Arial', 11, 'bold'),
                       relief='raised', bd=3, padx=15, pady=8)
    add_btn.pack(side=tk.LEFT, padx=5)
    
    release_btn = tk.Button(button_frame, text="➖ Release Pokémon", command=release_pokemon_gui,
                           bg='#CC0000', fg='white', font=('Arial', 11, 'bold'),
                           relief='raised', bd=3, padx=15, pady=8)
    release_btn.pack(side=tk.LEFT, padx=5)
    
    # Spacer
    tk.Label(button_frame, text="", bg='#FFDE00').pack(side=tk.LEFT, expand=True)
    
    save_btn = tk.Button(button_frame, text="💾 Save Collection", command=save_pokemons,
                        bg='#4CAF50', fg='white', font=('Arial', 11, 'bold'),
                        relief='raised', bd=3, padx=15, pady=8)
    save_btn.pack(side=tk.RIGHT, padx=5)
    
    # List frame with border
    list_frame = tk.Frame(main_frame, bg='#CC0000', relief='ridge', bd=3)
    list_frame.pack(fill=tk.BOTH, expand=True, pady=10)
    
    # Inner frame for treeview
    inner_frame = tk.Frame(list_frame, bg='white')
    inner_frame.pack(fill=tk.BOTH, expand=True, padx=2, pady=2)
    
    # Create treeview with pokemon style
    columns = ('id', 'name', 'type', 'level')
    tree = ttk.Treeview(inner_frame, columns=columns, show='headings', 
                       style="Pokemon.Treeview", height=15)
    
    # Configure columns
    tree.heading('id', text='ID')
    tree.heading('name', text='Name')
    tree.heading('type', text='Type')
    tree.heading('level', text='Level')
    
    tree.column('id', width=60, anchor=tk.CENTER)
    tree.column('name', width=200, anchor=tk.CENTER)
    tree.column('type', width=150, anchor=tk.CENTER)
    tree.column('level', width=100, anchor=tk.CENTER)
    
    # Add scrollbar
    scrollbar = ttk.Scrollbar(inner_frame, orient=tk.VERTICAL, command=tree.yview)
    tree.configure(yscroll=scrollbar.set)
    
    # Pack tree and scrollbar
    tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
    scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    
    # Status bar
    status_frame = tk.Frame(root, bg='#CC0000', relief='sunken', bd=1)
    status_frame.pack(side=tk.BOTTOM, fill=tk.X)
    
    status_var = tk.StringVar()
    status_var.set("Ready")
    status_bar = tk.Label(status_frame, textvariable=status_var, 
                         bg='#CC0000', fg='white', font=('Arial', 10),
                         anchor=tk.W, padx=10)
    status_bar.pack(fill=tk.X)
    
    # Add some tips
    tips_frame = tk.Frame(main_frame, bg='#FFDE00')
    tips_frame.pack(fill=tk.X, pady=5)
    
    tips_label = tk.Label(tips_frame, 
                         text="Tip: Click column headers to sort, double-click Pokémon to view details",
                         bg='#FFDE00', fg='#666666', font=('Arial', 9, 'italic'))
    tips_label.pack()
    
    # Bind double click to show pokemon details
    def on_item_double_click(event):
        item = tree.selection()[0]
        values = tree.item(item, 'values')
        if values:
            messagebox.showinfo("Pokémon Details", 
                              f"ID: {values[0]}\n"
                              f"Name: {values[1]}\n"
                              f"Type: {values[2]}\n"
                              f"Level: {values[3]}")
    
    tree.bind('<Double-1>', on_item_double_click)

if __name__ == "__main__":
    root = tk.Tk()
    create_widgets(root)
    init_data()
    refresh_list()
    root.mainloop()